<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/21 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

use yii\db\Migration;

/**
 * Class m210417_053502_menu
 */
class m210417_053502_menu extends Migration
{
    const TB_MENU_TPL = '{{%menu}}';
    const TB_MENU_ROLE_TPL = '{{%menu_role}}';
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable(self::TB_MENU_TPL, [
            'id' => $this->primaryKey()->unsigned()->unique(),
            'parent_id' => $this->integer(10)->unsigned()->defaultValue(0)->notNull()->comment('父级菜单id'),
            'name' => $this->string(32)->notNull()->defaultValue('')->comment('菜单名称'),
            'route' => $this->string(32)->unique()->notNull()->defaultValue('')->comment('菜单路由名称'),
            'description' => $this->string(128)->notNull()->defaultValue('')->comment('说明备注'),
            'sort_id' => $this->integer(10)->unsigned()->defaultValue(0)->notNull()->comment('排序'),
            'children' => $this->integer(10)->unsigned()->defaultValue(0)->notNull()->comment('下级菜单数量'),
            'created_at' => $this->dateTime()->notNull(),
            'updated_at' => $this->dateTime()->notNull(),
        ], $tableOptions . ' COMMENT "菜单表" ');

        $this->createTable(self::TB_MENU_ROLE_TPL, [
            'id' => $this->primaryKey()->unsigned()->unique(),
            'role' => $this->string(64)->notNull()->comment('角色名称'),
            'menu_id' => $this->integer(10)->unsigned()->notNull()->comment('菜单id'),

            'created_at' => $this->dateTime()->notNull()
        ], $tableOptions . ' COMMENT "菜单与角色绑定表" ');
        $this->createIndex('role_menu', self::TB_MENU_ROLE_TPL, ['role', 'menu_id'], true);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        if (YII_ENV_DEV) {
            $this->dropTable(self::TB_MENU_TPL);
            $this->dropTable(self::TB_MENU_ROLE_TPL);
            return true;
        }
        return false;
    }
}
